package com.qujia.station.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.alibaba.fastjson.JSONObject;
import com.qujia.common.config.QuJiaConfig;
import com.qujia.common.constant.UserConstants;
import com.qujia.common.core.controller.BaseController;
import com.qujia.common.core.domain.AjaxResult;
import com.qujia.common.core.domain.entity.SysUser;
import com.qujia.common.core.page.PageDomain;
import com.qujia.common.core.page.TableDataInfo;
import com.qujia.common.core.page.TableSupport;
import com.qujia.common.exception.BaseException;
import com.qujia.common.utils.SecurityUtils;
import com.qujia.station.domain.InventoryReportMonthly;
import com.qujia.station.domain.Station;
import com.qujia.station.domain.reportExcel.*;
import com.qujia.station.service.IStationService;
import com.qujia.station.service.InventoryReportMonthlyService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

@Api(tags = "进存销月报表")
@RestController
@RequestMapping("/inventoryReportMonthly")
@Slf4j
public class InventoryReportMonthlyController extends BaseController {

    @Autowired
    private InventoryReportMonthlyService inventoryReportMonthlyService;

    @Autowired
    private IStationService stationService;

    @PostMapping("/list")
    @ApiOperation(value = "查询进销存月报表", httpMethod = "POST")
    public TableDataInfo selectInventoryReportMonthlyList(@RequestBody InventoryReportMonthly inventoryReportMonthly){
        if(Objects.isNull(inventoryReportMonthly) || Objects.isNull(inventoryReportMonthly.getPageSize())
                || Objects.isNull(inventoryReportMonthly.getPageNum())){
            return failDataTable();
        }

        SysUser user = SecurityUtils.getLoginUser().getUser();
        if(Objects.isNull(user)){
            return failUserTable();
        }
        getStationList(inventoryReportMonthly,user);
        log.info("查询进销存月报表selectInventoryReportMonthlyList请求参数:[{}]", JSONObject.toJSONString(inventoryReportMonthly));
        PageDomain pageDomain = TableSupport.buildPageRequest();
        pageDomain.setPageNum(inventoryReportMonthly.getPageNum());
        pageDomain.setPageSize(inventoryReportMonthly.getPageSize());
        startPage(pageDomain);
        List<InventoryReportMonthly> inventoryReportMonthlies = inventoryReportMonthlyService.selectInventoryReportMonthlyList(inventoryReportMonthly);
        log.info("查询进销存月报表selectInventoryReportMonthlyList响应结果:[{}]", inventoryReportMonthlies.size());
        return getDataTable(inventoryReportMonthlies);
    }

    private void getStationList(InventoryReportMonthly inventoryReportMonthly, SysUser user){
        if(UserConstants.LEVEL_TWO.equals(user.getUserLevel())){
            if(Objects.nonNull(inventoryReportMonthly) && Objects.nonNull(inventoryReportMonthly.getStationId())){
                return;
            }
            List<Station> stationList = stationService.getStationByEnterpriseId(user.getEnterpriseId());
            if(CollectionUtils.isEmpty(stationList)){
                throw new BaseException("油企不存在");
            }
            List<Long> stationIdList = new ArrayList<>();
            for (Station station : stationList) {
                stationIdList.add(station.getStationId());
            }
            inventoryReportMonthly.setStationIdList(stationIdList);
        } else if(UserConstants.LEVEL_THREE.equals(user.getUserLevel())){
            inventoryReportMonthly.setStationId(user.getStationId());
        }
    }

    @PostMapping("/sum")
    @ApiOperation(value = "汇总进销存月报表", httpMethod = "POST")
    public AjaxResult inventoryReportMonthlySum(@RequestBody InventoryReportMonthly inventoryReportMonthly){
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if(Objects.isNull(user)){
            return AjaxResult.error("用户不存在，请重新登录");
        }
        getStationList(inventoryReportMonthly,user);
        log.info("汇总进销存月报表inventoryReportMonthlySum 请求参数：[{}]",JSONObject.toJSONString(inventoryReportMonthly));
        InventoryReportMonthly inventoryReportMonthlySum = inventoryReportMonthlyService.inventoryReportMonthlySum(inventoryReportMonthly);
        log.info("汇总进销存月报表inventoryReportMonthlySum 响应结果：[{}]",JSONObject.toJSONString(inventoryReportMonthlySum));
        return AjaxResult.success(inventoryReportMonthlySum);
    }

    @GetMapping("/task")
    @ApiOperation(value = "进销存月报表定时任务手动请求", httpMethod = "GET")
    public AjaxResult inventoryReportDailyTask(){
        inventoryReportMonthlyService.inventoryReportMonthlyStatistics();
        return AjaxResult.success();
    }

    @PostMapping("/export")
    @ApiOperation(value = "导出月报表", httpMethod = "POST")
    public AjaxResult exportInventoryReportMonthlyList(@RequestBody InventoryReportMonthly inventoryReportMonthly){
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if(Objects.isNull(user)){
            return AjaxResult.error("用户不存在，请重新登录");
        }
        getStationList(inventoryReportMonthly,user);
        log.info("导出月报表exportInventoryReportMonthlyList请求参数:[{}]", JSONObject.toJSONString(inventoryReportMonthly));

        List<InventoryReportMonthly> inventoryReportMonthlies = inventoryReportMonthlyService.selectInventoryReportMonthlyList(inventoryReportMonthly);
        log.info("导出月报表exportInventoryReportMonthlyList响应结果:[{}]", inventoryReportMonthlies.size());
        if(CollectionUtils.isEmpty(inventoryReportMonthlies)){
            return AjaxResult.error("月报表为空");
        }
        // excel 导出数据组装
        List<InventoryReportDto> inventoryReportMonthlyDtoList = new ArrayList<>();
        for (InventoryReportMonthly reportMonthly : inventoryReportMonthlies) {

            StartPeriodDto startPeriodDto = new StartPeriodDto();
            BeanUtils.copyProperties(reportMonthly,startPeriodDto);
            AddPeriodDto addPeriodDto = new AddPeriodDto();
            BeanUtils.copyProperties(reportMonthly,addPeriodDto);
            ReducePeriodDto reducePeriodDto = new ReducePeriodDto();
            BeanUtils.copyProperties(reportMonthly,reducePeriodDto);
            InventoryPeriodDto inventoryPeriodDto = new InventoryPeriodDto();
            BeanUtils.copyProperties(reportMonthly,inventoryPeriodDto);
            LastPeriodDto lastPeriodDto = new LastPeriodDto();
            BeanUtils.copyProperties(reportMonthly,lastPeriodDto);

            InventoryReportDto inventoryReportMonthlyDto = new InventoryReportDto();
            BeanUtils.copyProperties(reportMonthly,inventoryReportMonthlyDto);

            List<StartPeriodDto> startPeriodDtoList = new ArrayList<>();
            startPeriodDtoList.add(startPeriodDto);
            inventoryReportMonthlyDto.setStartPeriodDtoList(startPeriodDtoList);
            List<AddPeriodDto> addPeriodDtoList = new ArrayList<>();
            addPeriodDtoList.add(addPeriodDto);
            inventoryReportMonthlyDto.setAddPeriodDtoList(addPeriodDtoList);
            List<ReducePeriodDto> reducePeriodDtoList = new ArrayList<>();
            reducePeriodDtoList.add(reducePeriodDto);
            inventoryReportMonthlyDto.setReducePeriodDtoList(reducePeriodDtoList);
            List<InventoryPeriodDto> inventoryPeriodDtoList = new ArrayList<>();
            inventoryPeriodDtoList.add(inventoryPeriodDto);
            inventoryReportMonthlyDto.setInventoryPeriodDtoList(inventoryPeriodDtoList);
            List<LastPeriodDto> lastPeriodDtoList = new ArrayList<>();
            lastPeriodDtoList.add(lastPeriodDto);
            inventoryReportMonthlyDto.setLastPeriodDtoList(lastPeriodDtoList);

            inventoryReportMonthlyDtoList.add(inventoryReportMonthlyDto);
        }

        return AjaxResult.success(exportInventoryReportMonthly(inventoryReportMonthlyDtoList));
    }

    private String exportInventoryReportMonthly(List<InventoryReportDto> inventoryReportMonthlyDtoList){
        ExportParams params = new ExportParams(null, "月报表", ExcelType.XSSF);
        Workbook workbook = ExcelExportUtil.exportExcel(params, InventoryReportDto.class, inventoryReportMonthlyDtoList);
        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        String filename = "";
        OutputStream out = null;
        try {
            filename = encodingFilename("进销存月报表");
            out = new FileOutputStream(getAbsoluteFile(filename));
            workbook.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (workbook != null) {
                try {
                    workbook.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
        return filename;
    }

    private String encodingFilename(String filename) {
        filename = UUID.randomUUID().toString() + "_" + filename + ".xlsx";
        return filename;
    }

    public String getAbsoluteFile(String filename) {
        String downloadPath = QuJiaConfig.getDownloadPath() + filename;
        File desc = new File(downloadPath);
        if (!desc.getParentFile().exists()) {
            desc.getParentFile().mkdirs();
        }
        return downloadPath;
    }

}
